package com.dyrnq.seckill.controller;

import com.dyrnq.seckill.dto.LoginDTO;
import com.dyrnq.seckill.dto.SeckillGoodsDTO;
import com.dyrnq.seckill.dto.UserDTO;
import com.dyrnq.seckill.service.IUserService;
import com.dyrnq.seckill.service.impl.SeckillQueryService;
import com.dyrnq.seckill.util.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequiredArgsConstructor
public class WebController {

    private final SeckillQueryService seckillQueryService;
    private final IUserService userService;

    @Value("${app.jwt.secret}")
    String jwtSecret;

    @GetMapping("/")
    public String index(Model model) {
        List<SeckillGoodsDTO> seckillGoodsList = seckillQueryService.listSeckillGoodsDTO();
        model.addAttribute("goodsList", seckillGoodsList);
        return "index";
    }


    @GetMapping("/goods/detail/{goodsId}")
    public String goodsDetail(Model model, @PathVariable("goodsId") Long goodsId) {
        SeckillGoodsDTO goodsDTO = seckillQueryService.getSeckillGoodsDTO(goodsId);
        model.addAttribute("goods", goodsDTO);
        return "goods_detail";
    }

    @GetMapping("/about")
    public String about(Model model) {
        return "about";
    }

    @GetMapping("/login")
    public String login(Model model) {
        return "login";
    }

    @PostMapping(value = "/login", consumes = {"application/json"})
    @ResponseBody
    public Result<String> doLogin(HttpSession session, @RequestBody LoginDTO loginDTO) {
        UserDTO user = userService.login(loginDTO);
        session.setAttribute("user", user);
        Map<String, String> map = new HashMap<>();
        map.put(Claims.ID, user.getId() + "");
        String jwt = JwtUtils.generateToken(user.getUserName(), map, jwtSecret);
        return Result.success(jwt);
    }

    @RequestMapping(value = "/logout", consumes = {"application/json"})
    @ResponseBody
    public Result<String> doLogin(HttpSession session) {
        session.invalidate();
        return Result.success(null);
    }
    @GetMapping("/stomp")
    public String stomp(Model model) {
        return "stomp";
    }
}
